package com.example.mcu_up.serial;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.InvalidParameterException;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android_serialport_api.SerialPort;

public class Mcu_Serial {

	protected static SerialPort mSerialPort;
	protected OutputStream mOutputStream;
	private InputStream mInputStream;
	Handler handler;
	ReceiveThread mReceiveThread = new ReceiveThread();
	SendingThread mSendingThread = new SendingThread();
	HandleThread handleThread = new HandleThread();

	boolean isrunning = false;
	Queue<Mcu_Pack> sendqueue = new ConcurrentLinkedQueue<Mcu_Pack>();
	Queue<Mcu_Pack> readqueue = new ConcurrentLinkedQueue<Mcu_Pack>();

	public static Mcu_Serial serial;

	public Mcu_Serial() {
		try {
			mSerialPort = new SerialPort(new File("/dev/ttyS2"), 115200, 0);
			mOutputStream = mSerialPort.getOutputStream();
			mInputStream = mSerialPort.getInputStream();
		} catch (InvalidParameterException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}

	/*
	 * 这个方法是设置端口的
	 */
	public void setSerialPort(String dev, int port) {
		try {
			mSerialPort = new SerialPort(new File(dev), port, 0);
		} catch (SecurityException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}

	public static Mcu_Serial getInstance() {
		if (serial == null) {
			serial = new Mcu_Serial();
		}
		return serial;
	}

	public void setHandler(Handler handler) {
		this.handler = handler;
	}

	/**
	 * 开启串口相关的工作线程
	 */
	public void start() {

		isrunning = true;
		if (mSerialPort != null) {

			if (!mSendingThread.isAlive()) {
				mSendingThread.start();
			}
			if (!mReceiveThread.isAlive()) {
				mReceiveThread.start();
			}
			if (!handleThread.isAlive()) {
				handleThread.start();
			}
		}
	}

	/**
	 * 关闭串口相关的工作线程
	 */
	public void stop() {

		isrunning = false;
		if (mSendingThread != null) {
			try {
				mSendingThread.join(500);
				mSendingThread.interrupt();
				mSendingThread = null;
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		if (mReceiveThread != null) {
			try {
				mReceiveThread.join(500);
				mReceiveThread.interrupt();
				mReceiveThread = null;
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		if (handleThread != null) {
			try {
				handleThread.join(500);
				handleThread.interrupt();
				handleThread = null;
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	int t = 0;

	private class ReceiveThread extends Thread {
		Mcu_Pack p = null;

		@Override
		public void run() {
			super.run();
			Log.d("mytestpack", "receive thread is running");
			while (isrunning) {
				byte[] buffer = new byte[32];
				try {

					/*
					 * int size=mInputStream.read(buffer); if(size>0)
					 * 
					 * Log.i("mygetdate",byteToString(buffer, size));
					 */

					if (mInputStream == null) {
						throw new NoInput("串口未初始化！");
					}

					p = new Mcu_Pack();
					p = p.getPack(mInputStream);

					readqueue.add(p);
					Log.d("index11", "" + t++);

				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (NoInput e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (BadPackageException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}
	}

	static int i = 0;

	// int是十六进制的数
	public void send(Mcu_Pack p) {
		sendqueue.add(p);

	}

	public class SendingThread extends Thread {
		@Override
		public void run() {

			while (isrunning) {
				try {

					Mcu_Pack p = sendqueue.poll();
					if (p == null) {
						try {
							Thread.sleep(50);
							continue;
						} catch (InterruptedException e) {

						}
					}
					if (mOutputStream != null) {
						mOutputStream.write(p.tobytes());

					} else {
						return;
					}
				} catch (IOException e) {
					e.printStackTrace();
					return;
				}
			}
		}

	}

	public class HandleThread extends Thread {

		public void run() {
			// TODO 自动生成的方法存根
			super.run();
			while (isrunning) {
				Mcu_Pack p = readqueue.poll();

				if (p == null) {
					try {
						Thread.sleep(50);
						continue;
					} catch (InterruptedException e) {
					}
				} else {

					Message message = new Message();
					message.arg1 = -6;
					message.obj = p;
					handler.sendMessage(message);
				}
			}
		}
	}

	public void closeSerialPort() {
		if (mSerialPort != null) {
			mSerialPort.close();
			mSerialPort = null;
		}

	}

	public static String byteToString(byte[] b, int len) {
		StringBuffer buffer = new StringBuffer(len);
		for (int i = 0; i < len; i++) {
			String strHex = Integer.toHexString(b[i]).toUpperCase();
			if (strHex.length() > 3) {
				buffer.append(strHex.substring(6) + " ");
			} else if (strHex.length() < 2) {
				buffer.append("0" + strHex + " ");

			} else {
				buffer.append(strHex + " ");
			}
		}
		return buffer.toString();

	}
}
